package com.dyzx.hbb.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyzx.hbb.modules.wms.entity.WmsInventory;
import com.dyzx.hbb.modules.wms.entity.WmsStockInDetails;
import com.dyzx.hbb.modules.wms.entity.WmsStockOutDetails;
import com.dyzx.hbb.modules.wms.mapper.WmsInventoryMapper;
import com.dyzx.hbb.modules.wms.service.WmsInventoryService;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @description 针对表【wms_inventory(库存表（核心库存数据）)】的数据库操作Service实现
 * @createDate 2025-06-01 17:40:28
 */
@Service
public class WmsInventoryServiceImpl extends ServiceImpl<WmsInventoryMapper, WmsInventory>
        implements WmsInventoryService {

    @Override
    public WmsInventory addInventory(WmsStockInDetails detail) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        LambdaUpdateWrapper<WmsInventory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmsInventory::getProductId, detail.getProductId());
        wrapper.last("limit 1");
        WmsInventory inventory = this.getOne(wrapper);
        if (inventory == null) {
            inventory = new WmsInventory();
            inventory.setOrganId(organId);
            inventory.setOperatorId(userId);
            inventory.setPrice(detail.getUniPrice());
            inventory.setProductId(detail.getProductId());
            inventory.setQuantity(detail.getQuantity());
            inventory.setLocationId(detail.getLocationId());
            inventory.setLocationAreaId(detail.getLocationAreaId());
            inventory.setHouseId(detail.getHouseId());
            inventory.setPrice(detail.getUniPrice());
            this.save(inventory);
        } else {
            inventory.setQuantity(inventory.getQuantity() + detail.getQuantity());
            this.updateById(inventory);
        }
        return inventory;
    }

    @Override
    public WmsInventory getInventory(WmsStockOutDetails detail) {
        LambdaUpdateWrapper<WmsInventory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmsInventory::getProductId, detail.getProductId());
        wrapper.last("limit 1");
        WmsInventory inventory = this.getOne(wrapper);
        if (inventory != null) {
           // inventory = new WmsInventory();
            if (detail.getQuantity() > 0 && inventory.getQuantity() >= detail.getQuantity()) {
                inventory.setQuantity(inventory.getQuantity() - detail.getQuantity());
                this.updateById(inventory);
            } else {
                throw new RuntimeException(" 数量不足，库存数量为：" + inventory.getQuantity() + "，出库数量为：" + detail.getQuantity() + "，无法完成出库操作。");
            }
        }
        return inventory;
    }
}




